/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-script-url */
/* eslint-disable array-callback-return */
// 客户模糊查询
import React, { PureComponent } from 'react';
import { DownOutlined, UpOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Row, Button, Col, Input, Divider, Dropdown, Menu, Modal, Badge, Form } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import styles from '@/utils/utils.less';
import downloadFile from '@/utils/utils';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import AssociatedCustomer from '@/pages/components/AssociatedCustomerWithState';
import InjuryList from './InjuryList';
import BigwareList from './Bigwarelist';
import DictCode from '../../components/DictCode';

const { confirm } = Modal;
const FormItem = Form.Item;
@connect(({ bigaccomanage, injuryware, loading }) => ({
  loading: loading.effects['injuryware/fetchInjuryPageList'],
  listLoading: loading.effects['bigaccomanage/fetchInsSearchList'],
  tabList: injuryware.tabList,
  activeKey: injuryware.activeKey,
  pageData: injuryware.pageData,
  formFieldsValue: injuryware.formFieldsValue,
  expandForm: injuryware.expandForm,
  bigwareList: bigaccomanage.bigwareList,
  selectedRowKeys: bigaccomanage.selectedRowKeys,
  selectedRows: bigaccomanage.selectedRows,
}))
class InjuryWare extends PureComponent {
  formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      stateMap: ['', 'default', 'success', 'warning'],
      excelLoading: false,
    };
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount = () => {
    const {
      isMenuLink,
      pageData: { pagination },
    } = this.props;
    if (isMenuLink) {
      this.resetAndGeLlist();
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  };

  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'injuryware/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 重置
  resetSearch = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'injuryware/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
  };

  getList = async (currentPage = 1, pageSize = 10) => {
    const { dispatch } = this.props;
    try {
      const fieldsValue = await this.formRef.current.validateFields();
      dispatch({
        type: 'injuryware/fetchInjuryPageList',
        payload: {
          injSecAcco: {
            injSecAccoCode: fieldsValue.injSecAccoCode && fieldsValue.injSecAccoCode.trim(),
            state: fieldsValue.state && fieldsValue.state.trim(),
            insAccoId: fieldsValue.injInsAccoId && fieldsValue.injInsAccoId.trim(),
            injSecAccoId: fieldsValue.injSecAccoId && fieldsValue.injSecAccoId.trim(),
          },
          pageArg: {
            currentPage,
            pageSize,
          },
          mdCustId: fieldsValue.mdCustId?.key,
        },
      });
    } catch (error) {
      console.error(error);
    }
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bigaccomanage/updateModelData',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 获取大库列表
  onSearch = value => {
    const { dispatch } = this.props;
    if (value.trim().length) {
      dispatch({
        type: 'bigaccomanage/fetchInsSearchList',
        payload: { accoName: value.trim() },
      });
    }
  };

  // - 新增
  invoiceApply = () => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/addinjury`);
  };

  batchMaintenance = () => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/injurybatch`);
  };

  exportPage = () => {
    const { selectedRowKeys, formFieldsValue } = this.props;
    const url = '/mgrApi/injSecAccoApi/expInjSecAcco';
    if (selectedRowKeys.length) {
      this.setState({
        excelLoading: true,
      });
      downloadFile(
        {
          injSecAccoIds: selectedRowKeys,
        },
        url,
        'POST',
        () => {
          this.setState({
            excelLoading: false,
          });
        }
      );
    } else {
      confirm({
        title: '温馨提示',
        icon: <ExclamationCircleOutlined />,
        content: '请选择数据，如不选择，默认导出当前条件下所有数据！',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          downloadFile(formFieldsValue, url, 'POST');
        },
      });
    }
  };

  // 查询
  goSearch = async () => {
    const { dispatch } = this.props;
    try {
      const formFieldsValue = await this.formRef.current.validateFields();
      const tempValues = {};
      Object.keys(formFieldsValue).forEach(key => {
        tempValues[key] =
          formFieldsValue[key] === undefined || formFieldsValue[key] === null
            ? null
            : formFieldsValue[key];
      });
      dispatch({
        type: 'injuryware/updateModelData',
        payload: { formFieldsValue: tempValues },
      });
      this.getList();
    } catch (error) {
      console.error(error);
    }
  };

  warningMpdfiy = record => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/editinjury?injSecAccoId=${record.injSecAccoId}`);
  };

  linkRoute = record => {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/detailinjury?injSecAccoId=${record.injSecAccoId}`);
  };

  removeItem = record => {
    const { dispatch } = this.props;
    confirm({
      title: '你确定要删除此二级户信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk() {
        dispatch({
          type: 'injuryware/deleteInjury',
          payload: { injSecAccoId: record.injSecAccoId },
        });
      },
      onCancel() {},
    });
  };

  // 修改状态
  updateItem = record => {
    const { dispatch } = this.props;
    const title =
      Number(record.state) === 2
        ? '你确定要停用此大库吗？'
        : '启用后，‘所属大库、二级户编码、关联客户’将不可修改，确定启用吗？';
    // const warnMessage = Number(record.state) === 2 ? '停用成功' : '启用成功';
    confirm({
      title,
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'injuryware/updateStatus',
          payload: { injSecAccoId: record.injSecAccoId, state: record.state },
        });
        // mgrAxios('/injSecAccoApi/updateState', { injSecAccoId: record.injSecAccoId })
        //   .then(res => {
        //     console.log('启用/停用默认', res);
        //     if (res.success == true) {
        //       message.success(warnMessage);
        //       _this.getList(_this.state.nowPage, _this.state.pageSizes);
        //     } else {
        //       message.error(res.message);
        //     }
        //   })
        //   .catch(err => {});
      },

      onCancel() {},
    });
  };

  // 选择关联客户
  handleChange = (selectValue, options) => {
    console.log('此处选择', options);
    if (options) {
      this.formRef.current.setFieldsValue({ mdCustId: options });
    }
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist() {
    await this.resetSearch();
    await this.getList();
  }

  renderAdvancedForm() {
    const { formFieldsValue, listLoading, bigwareList } = this.props;
    return (
      <Form ref={this.formRef} layout="inline" initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="二级户编码" name="injSecAccoCode" {...this.formItemLayout}>
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="二级户名称" name="injSecAccoId" {...this.formItemLayout}>
              <InjuryList placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="大库名称" name="injInsAccoId" {...this.formItemLayout}>
              <BigwareList
                placeholder="请输入"
                onSearch={this.onSearch}
                bigwareList={bigwareList}
                loading={listLoading}
              />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="账户状态" name="state" {...this.formItemLayout}>
              <DictCode dictType="COMMON_ENABLED_STATUS" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="关联客户名称" name="mdCustId" {...this.formItemLayout}>
              <AssociatedCustomer handleChange={this.handleChange} />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right' }}>
                <Button type="primary" htmlType="submit" onClick={() => this.goSearch()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderSimpleForm() {
    const { formFieldsValue } = this.props;
    return (
      <Form ref={this.formRef} layout="inline" initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="二级户编码" name="injSecAccoCode" {...this.formItemLayout}>
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="二级户名称" name="injSecAccoId" {...this.formItemLayout}>
              <InjuryList placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.goSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { stateMap, excelLoading } = this.state;
    const { loading, pageData = [], selectedRows = [], selectedRowKeys = [] } = this.props;
    const injuryColumns = [
      {
        title: '二级户编码',
        dataIndex: 'injSecAccoCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '二级户名称',
        width: '25%',
        dataIndex: 'injSecAccoName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '所属大库',
        dataIndex: 'insAccoName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => text || '--',
      },
      {
        title: '浮动费率(%)',
        dataIndex: 'floatFeeRatio',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '账户状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <Badge key={record.state} status={stateMap[record.state]} text={text} />
        ),
      },
      {
        title: '操作',
        width: 150,
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <Authorized authority="business:injSecAccoApi:update" noMatch={null}>
              <span
                style={{ color: '#1890FF', cursor: 'pointer' }}
                onClick={() => this.warningMpdfiy(record)}
              >
                {' '}
                修改
              </span>
              <Divider type="vertical" />
            </Authorized>
            {checkPermissions([
              'business:injSecAccoApi:delete',
              'business:injSecAccoApi:updateState',
            ]) ? (
              <Dropdown
                overlay={
                  <Menu>
                    <Menu.Item key="view">
                      <a onClick={() => this.linkRoute(record)}> 查看</a>
                    </Menu.Item>
                    {record.stateName === '待启用' &&
                      checkPermissions('business:injSecAccoApi:delete') && (
                        <Menu.Item key="delete" onClick={() => this.removeItem(record)}>
                          删除
                        </Menu.Item>
                      )}
                    {checkPermissions('business:injSecAccoApi:updateState') && (
                      <Menu.Item key="able" onClick={() => this.updateItem(record)}>
                        {Number(record.state) === 2 ? '停用' : '启用'}
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多 <DownOutlined />
                </a>
              </Dropdown>
            ) : (
              <a href="javascript:;" onClick={() => this.linkRoute(record)}>
                {' '}
                查看
              </a>
            )}
            {/* <Dropdown
              overlay={
                <Menu>
                  <Menu.Item key="view">
                    <a onClick={() => this.linkRoute(record)}> 查看</a>
                  </Menu.Item>
                  {checkPermissions('business:injSecAccoApi:delete') && (
                    <Menu.Item key="delete" onClick={() => this.removeItem(record)}>
                      删除
                    </Menu.Item>
                  )}
                  {checkPermissions('business:injSecAccoApi:updateState') && (
                    <Menu.Item key="able" onClick={() => this.updateItem(record)}>
                      {Number(record.state) === 2 ? '停用' : '启用'}
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多 <Icon type="down" />
              </a>
            </Dropdown> */}
          </div>
        ),
      },
    ];
    return (
      <div>
        <div
          className={styles.tableListForm}
          style={{
            margintop: 4,
            marginBottom: 16,
            paddingTop: 24,
            paddingRight: 24,
            backgroundColor: '#fafafa',
          }}
        >
          {this.renderForm()}
        </div>
        {(checkPermissions('business:injSecAccoApi:insert') ||
          checkPermissions('business:injSecAccoApi:upload') ||
          checkPermissions('business:injSecAccoApi:expInjSecAcco')) && (
          <Row style={{ marginBottom: 16 }}>
            <Authorized authority="business:injSecAccoApi:insert" noMatch={null}>
              <Button type="primary" onClick={this.invoiceApply} style={{ marginRight: 8 }}>
                新增
              </Button>
            </Authorized>
            <Authorized authority="business:injSecAccoApi:upload" noMatch={null}>
              <Button onClick={this.batchMaintenance} style={{ marginRight: 8 }}>
                批量维护浮动费率
              </Button>
            </Authorized>
            <Authorized authority="business:injSecAccoApi:expInjSecAcco" noMatch={null}>
              <Button onClick={this.exportPage} loading={excelLoading}>
                导出
              </Button>
            </Authorized>
          </Row>
        )}
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          data={pageData}
          columns={injuryColumns}
          rowKey="injSecAccoId"
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
  }
}
export default InjuryWare;
